<?php


namespace app\plugin\controller\article;


use app\common\controller\AppCommon;
use app\plugin\controller\article\com\Article;
use app\plugin\controller\article\service\OrderService;
use app\service\CommonUser;
use app\service\DiyLog;
use app\service\Page;
use base\WeixinAgent;
use think\Controller;
use think\Request;
include_once EXTEND_PATH.'base/WeixinAgent.php';
class Client extends Article
{


    public function index()
    {
        $pageSize = 10;
        $page = !empty($this->param['page']) ? intval($this->param['page']) : 1;
        $cid = !empty($this->param['cid']) ? intval($this->param['cid']) : '';
        $keyword = !empty($this->param['keyword']) ? trim(strip_tags($this->param['keyword'])) : '';
        $from = !empty($this->param['from']) ? trim(strip_tags($this->param['from'])) : '';
        $author = !empty($this->param['author']) ? trim(strip_tags($this->param['author'])) : '';
        $where = ['status' => 1];
        if (!empty($cid)) {
            $where['category_id'] = $cid;
        }
        if (!empty($keyword)) {
            $where['title'] = ['like', '%' . $keyword . '%'];
        }
        if (!empty($author)) {
            $where['author'] = $author;
        }
        if ($from === 'buy') {

            $buyLog = AppCommon::data_list_nopage('plugin_article_order', ['uid' => $this->uid, 'status' => 1], 'aid');
            if (empty($buyLog)) {
                //默认
                $where['aid'] = 'abc';
                return $this->error('暂无购买记录，或未登录', null, '', 2);
            } else {
                $where['aid'] = ['in', array_column($buyLog, 'aid')];
            }


        }
        $data = AppCommon::data_list('plugin_article', $where, $page . ',' . $pageSize, 'id,aid,title,add_time,count_view,price,category_id,author,sale_count', 'id desc');

        $ids = AppCommon::db('plugin_article')->where(['status' => 1, 'category_id' => ['>', 0]])->field('category_id')->group('category_id desc')->select();
        if (!empty($ids)) {
            $category = AppCommon::data_list_nopage('plugin_article_category', ['id' => ['in', array_column($ids, 'category_id')]]);
            $this->assign('category', $category);
        }

        if ($data) {
            foreach ($data as &$v) {
                $v['category_name'] = AppCommon::data_get_column('plugin_article_category', ['id' => $v['category_id']], 'name');
                $v['buy_status'] = AppCommon::data_get('plugin_article_order', ['uid' => $this->uid, 'aid' => $v['aid'], 'status' => 1], 'status');
                if (empty($v['count_view'])) {
                    $v['count_view'] = 1;
                }
            }
            unset($v);
        }


        $total = AppCommon::data_count('plugin_article', $where);

        $this->assign('page', Page::set($data, $pageSize, $page, $total, $this->param, url()));

        $hot_data = AppCommon::data_list('plugin_article', ['status' => 1], '1,10', 'id,aid,title,add_time,count_view,price,category_id,author,sale_count', 'sale_count desc,count_view desc,id desc');

        $this->assign('data', $data);
        $this->assign('hot_data', $hot_data);
        return $this->fetch();
    }

    public function detail($get = false)
    {
        if (empty($this->param['apath'])) {
            return $this->error('文章已下线');
        }
        $data = AppCommon::data_get('plugin_article', ['aid' => $this->param['apath']]);
        if ($get) {
            return $data;
        }
        if (empty($data) || empty($data['status'])) {
            return $this->error('文章已下线');
        }

        $data['content'] = htmlspecialchars_decode($data['content']);
        $data['category_name'] = AppCommon::data_get_column('plugin_article_category', ['id' => $data['category_id']], 'name');


        AppCommon::data_update('plugin_article', ['id' => $data['id']], ['count_view' => $data['count_view'] + 1]);
        if (empty($data['count_view'])) {
            $data['count_view'] = 1;
        }
        if (!empty($data['category_id'])) {
            $recommend = AppCommon::data_list('plugin_article', ['status' => 1, 'category_id' => $data['category_id'], 'id' => ['<>', $data['id']]], '1,10', 'id,aid,title,add_time,count_view,price,category_id,author,sale_count,desc', 'sale_count desc,count_view desc,id desc');

        }


        $order = AppCommon::data_get('plugin_article_order', ['uid' => $this->uid, 'aid' => $data['aid'], 'status' => 1], 'id');
        if (empty($order)) {
            $data['content'] = '<br><div class="but-btn" style="text-align: center"><a data-apath="' . $data['aid'] . '" href="javascript:pay(\'' . $data['aid'] . '\')" class="bs-btn bs-green">阅读全文(' . $data['price'] . '元)</a></div>';
        }


        $this->assign('recommend', $recommend);
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function buy()
    {
        $data = $this->detail(true);
        if (empty($data) || $data['status'] <> 1) {
            data_return('已下线', -1);
        }
        if (empty($this->uid)) {
            $uri = !IS_AJAX ? urlencode(URL_HTTP . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']) : URL_WEB . ltrim(url('/plugin/article.client/detail', ['apath' => $data['aid']]), '/');
            $loginUrl = URL_WEB . ltrim(url('/console/account/wx_login'), '/');
            $loginUrl = $loginUrl . '?bs_redirect_uri=' . $uri;
            if (IS_AJAX || IS_POST) {
                data_return('登录超时，正在跳转页面...', 0, ['url' => $loginUrl]);
            } else {
                return $this->redirect($loginUrl, [], 4003);
            }
        }

        $order = AppCommon::data_get('plugin_article_order', ['uid' => $this->uid, 'aid' => $data['aid'], 'status' => 1], 'id');
        if (!empty($order)) {
            data_return('您已购买本文章，请刷新页面', -1);
        }
        //todo 清理未支付订单

        if (fromClient() <> 'weixin') {
            //
        }
        $this->param['channel'] = 'gzh';
        $arg = [
            'price' => $data['price'],
            'uid' => $this->uid,
            'aid' => $data['aid'],
        ];
        $order = OrderService::create($arg);
        if ($order['code'] <> 0) {
            data_return($order['msg'], $order['code']);
        }
        $akey = 'uqhmv7c6qc';
        $asecret = '11af5c27f5c8d5678a04cbqsf2620586';

        $user = CommonUser::get($this->uid, 'openid_wx');
        if (empty($user['openid_wx'])) {
            CommonUser::session_del($this->uid);
            data_return('目前仅支持绑定微信的用户购买', -1);
        }
        $openid = $user['openid_wx'];
        $chancel = 'wx_pub';
        $data = [
            'openid' => $openid,
            'outId' => $order['data']['order_sn'],
            'total_price' => $arg['price'],
            'body' => '支持知识付费',
            'channel' => $chancel,//支付渠道
            'client_type' => 'weixin',
            'timeout' => 900,
            'akey' => $akey,
            'asecret' => $asecret,
            'redirect_url' => URL_WEB . trim(url('/plugin/article.client/detail'), '/') . '?apath=' . $data['aid'],
            'call_back_url' => URL_WEB . trim(url('/plugin/article.payment/notify'), '/'),
            'use_return' => true
        ];
        $res = (new WeixinAgent())->Pay($data);

        if ($res['code'] <> 0) {
            data_return($res['msg'], -1);
        }

        data_return('创建订单成功，正在到支付页面...', 0, ['url' => $res['url'], 'order_sn' => $res['order_sn']]);
    }
}